// pages/zpba/zpba.js
const app = getApp()
const db = wx.cloud.database()
const $ = db.command.aggregate
const _ = db.command
var currentPage = 0
var itemsPerPage = 20 // 每页显示数量
var totalRecords = 0

Page({
  /**
   * 页面的初始数据
   */
  data: {
    top_label:[
      {
        name:'添加',
        color:'lightgreen'
      },
      {
        name:'删除',
        color:'lightgreen'
      },
      {
        name:'修改',
        color:'lightgreen'
      },
    ],
    goodslist:[],
    choicenumber:0,
    choicevalue:0,
    valuearray:[],
    p_choice:0,
  },

  //三选一
  sanxuanyi(e){
    //setData给动态下标数组的写法
    var index = "top_label[" + e.currentTarget.dataset.number + "].color"
    this.setData({
      'top_label[0].color':'lightgreen',
      'top_label[1].color':'lightgreen',
      'top_label[2].color':'lightgreen',
      [index]:'grey',
      p_choice:e.currentTarget.dataset.number
    })
  },

  //勾选
  checkboxChange: function (e) {
    this.data.choicenumber = e.detail.value.length
    this.data.choicevalue = e.detail.value
    this.data.valuearray = e.detail.value //数组形式
    console.log(e.detail.value)
  },
  //获得更多数据
  getMore(){
    var that = this
    const skipValue = currentPage * itemsPerPage;
    if(skipValue<=totalRecords){
      db.collection('goods')
      .where({
        block:wx.getStorageSync('block')
      })
      .skip(skipValue)
      .limit(itemsPerPage)
      .get({
        success: res => {
          currentPage++;
          if (res.data.length === 0 || (skipValue + res.data.length) >totalRecords) {
              console.log('All data has been loaded.');
          } else {
            that.data.goodslist.push(...res.data)
            that.setData({
              goodslist:that.data.goodslist
            })
            console.log(that.data.goodslist)
          }
        },
        fail: err => {
            console.error('Error loading more data:', err);
        }
      });
    }


  },
  //确认
  confirm(){
    var that = this
    //判断是否有资格修改gifts数据（库管、管理员）
    db.collection('staff')
    .where({
      mobile:app.globalData.mobile
    })
    .get({
      success(res){
        console.log('权限',res.data[0].station)
        if(res.data[0].station == '库管'|| res.data[0].station == '管理员'){
          //修改
          if(that.data.p_choice == 2){
            if(that.data.choicenumber == 1){
              wx.navigateTo({
                url: '/pages/goods_prefect/goods_prefect?name='+that.data.choicevalue,
              })
            }else{
              wx.showModal({
                title: '提醒',
                content: '信息修改只能单选！',
                showCancel: false
              })
            }
          }
          //添加
          else  if(that.data.p_choice == 0){
            wx.redirectTo({
              url: '/pages/goods/goods',
            })
          }
          //删除
          else if(that.data.p_choice == 1){
            // console.log(that.data.valuearray)
            db.collection('goods')
            .where({
              name:_.in(that.data.valuearray)
            })
            .remove()
            .then(res=>{console.log(res)}
            )
          }
        }else{
          wx.showModal({
            title: '提醒',
            content: '您不是库管，不能进行该操作！',
            showCancel: false
          })
        }
      }
    })

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    var that = this
    // 先获取总记录数
    db.collection('goods').where({
      block:wx.getStorageSync('block')
    }).count().then(res => {
      totalRecords = res.total;
      that.getMore();
    }).catch(err => {
      console.error('Failed to get the total count:', err);
    });
    // db.collection('goods')
    // .where({
    //   block:wx.getStorageSync('block') //app.globalData.block
    // })
    // .get({
    //   success(res){
    //     console.log(res.data)
    //     that.setData({
    //       goodslist:res.data
    //     })
    //   }
    // })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})